<template>
  <div class="address-book-container">
    <xr-new-header
      :content.sync="searchInput"
      placeholder="请输入员工姓名/手机号"
      show-search
      @search="headerSearch"
    >
      <div slot="ft">
        <el-button
          type="primary"
          icon="el-icon-user-solid"
          @click="asyncAddress"
          v-if="hasAsyncAddress"
          >同步通讯录</el-button
        >
      </div>
    </xr-new-header>
    <div class="btn_content">
      <el-table
        v-loading="loading"
        :data="tableData"
        :height="tableHeight"
        class="emp_table"
      >
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.field"
          :label="item.value"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="wechat" label="微信">
          <template slot-scope="scope" v-if="scope.row.wechat">
            <span class="wx_style">{{ scope.row.wechat }}</span>
            <el-button type="text" @click="copyText(scope.row.wechat)"
              >复制</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="wechatCodeUrl" label="微信二维码">
          <template slot-scope="scope" v-if="scope.row.wechatCodeUrl">
            <el-image
              :src="baseImgUrl + scope.row.wechatCodeUrl"
              :preview-src-list="[baseImgUrl + scope.row.wechatCodeUrl]"
              style="
                width: 34px;
                height: 34px;
                margin-right: 11px;
                vertical-align: middle;
              "
            >
            </el-image>
            <el-button type="text" @click="downloadsFile(scope.row)"
              >下载</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          show-overflow-tooltip
         
        >
        </el-table-column>
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          background
          layout="prev, pager, next, sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import XrNewHeader from "@/components/XrNewHeader";
import { copyText, downloadFileWithBuffer } from "@/utils";
import {
  adminAddressBookListApi,
  synchronousAddressBookApi,
} from "@/api/addressBook/addressBook";
import { downloadFileAPI } from "@/api/common";
import { mapGetters } from "vuex";
export default {
  components: {
    XrNewHeader,
  },
  data() {
    return {
      searchInput: "", // 搜索
      tableHeight: document.documentElement.clientHeight - 263, // 表的高度
      /** 分页逻辑 */
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 45, 60],
      total: 0,
      /** ** */
      fieldList: [
        { field: "realname", value: "姓名", width: "150" },
        { field: "username", value: "手机号", width: "150" },
        { field: "deptName", value: "所属部门", type: "select", width: "100" },
      ],
      loading: false, // 表的加载动画
      tableData: [],
      copyText: copyText,
      baseImgUrl: "",
    };
  },
  mounted() {
    this.baseImgUrl = this.$baseImgUrl;
    var self = this;
    /** 控制table的高度 */
    window.onresize = function () {
      self.tableHeight = document.documentElement.clientHeight - 263;
    };
    this.getAddressList();
  },
  computed: {
    ...mapGetters(["address"]),
    hasAsyncAddress() {
      return (
        this.address &&
        this.address.addressBook &&
        this.address.addressBook.synchronous
      );
    },
  },
  methods: {
    /**
     * 获取列表数据
     */
    async getAddressList() {
      this.loading = true;
      const { data } = await adminAddressBookListApi({
        page: this.currentPage,
        limit: this.pageSize,
        searchData: this.searchInput.trim(),
      });
      this.tableData = data.list;
      this.total = data.totalRow;
      this.loading = false;
    },
    /**
     * 搜索
     */
    headerSearch() {
      this.currentPage = 1;
      this.getAddressList();
    },
    /**
     * 同步通讯录
     */
    asyncAddress() {
      synchronousAddressBookApi().then((res) => {
        if (res.code == 0) {
          this.headerSearch();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    /**
     * 下载微信二维码
     */
    downloadsFile(row) {
      // const image = new Image();
      // image.crossOrigin = "anonymous"; // 设置跨域属性，避免出现跨域问题
      // image.src = this.baseImgUrl + row.wechatCodeUrl;
      // image.onload = function () {
      //   const canvas = document.createElement("canvas");
      //   canvas.width = image.width;
      //   canvas.height = image.height;
      //   const ctx = canvas.getContext("2d");
      //   ctx.drawImage(image, 0, 0, image.width, image.height);
      //   const downloadLink = document.createElement("a");
      //   downloadLink.href = canvas.toDataURL("image/jpeg");
        let imgType = row.wechatCodeUrl.slice(row.wechatCodeUrl.indexOf("."));
      //   downloadLink.download = `${row.realname}-微信二维码${imgType}`;
      //   document.body.appendChild(downloadLink);
      //   downloadLink.click();
      //   document.body.removeChild(downloadLink);
      // };
      downloadFileAPI(row.wechatDownUrl)
        .then((res) => {
          const blob = new Blob([res.data], {
            type: "",
          });
          downloadFileWithBuffer(blob, `${row.realname}-微信二维码${imgType}`);
        })
        .catch(() => {});
    },
    /**
     * 更改每页展示数量
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAddressList();
    },

    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAddressList();
    },
  },
};
</script>
<style scoped lang="scss">
.address-book-container {
  .btn_content {
    background: #fff;
    padding: 16px;
    .wx_style {
      display: inline-block;
      margin-right: 16px;
      //   width: 100px;
      //   overflow: hidden;
      //   text-overflow: ellipsis;
      //   white-space: nowrap;
    }
  }
}
</style>